<template>
    <div class="creat_box">
        <h2 style="text-align:center">{{ id ? '编辑文章' : "新建文章" }}</h2>
        <h6>上传图片</h6>
        <div class="upload_box">
            <UpLoad url="/api/upload" @finish='finish' :defaultImg="defultImg()" :beforeUpload="beforeUpload"
                :onErr="onErr" />
        </div>
        <From :fromData="fromData" sumbit="发表文章" :from="from" @on-sumbit="inputSumbit" />
    </div>
</template>

<script lang='ts'>
interface inputResult {
    title: string
    content: string
}
interface pushData {
    "title": string,
    "content": string,
    "image"?: string,
    "column"?: string,
    "author"?: string
}
import { computed, defineComponent, onMounted, ref } from 'vue'
import From, { FromProps, useFrom } from '../../components/From/index.vue'
import UpLoad, { result, beforeUpload, onErr } from '../../components/UpLoad/index.vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { reqAddPost, reqSomePost, reqChangePost } from '../../api/main'
import { Message } from '../../coustom/Message'
interface postData {
    "_id": string,
    "title": string,
    "excerpt": string,
    "content": string,
    "image"?: {
        "_id": string,
        "url": string,
        "createdAt": string
    },
    "author": {
        "_id": string,
        "email": string,
        "nickName": string,
        "description": string,
        "avatar": {
            _id: string
            url: string
        }
        "column": string,
        "createdAt": string
    },
    "column": string,
    "createdAt": string
}
export default defineComponent({
    name: 'Create',
    components: { UpLoad, From },
    setup() {
        const from = useFrom()
        const { params } = useRoute()
        const { push } = useRouter()
        const postData = ref<postData | null>(null)
        const { id } = params
        const getPost = async () => {
            try {
                if (id) {
                    const result = await (await reqSomePost(id as string)).data as postData
                    postData.value = result
                    from.setValue({
                        title: result.title,
                        content: result.content
                    })
                }
            } catch (err) {
                Message.error('出错啦' + err)
            }
        }
        const store = useStore()
        const fromData: FromProps = [
            {
                titel: '标题',
                inputType: 'text',
                valueKey: 'title',
                rules: [
                    {
                        type: 'required',
                        text: '标题是必填项'
                    }
                ]
            },
            {
                titel: '正文',
                valueKey: 'content',
                inputType: 'textarea',
                row: 8,
                rules: [
                    {
                        type: 'required',
                        text: '正文是必填项'
                    }
                ]
            }
        ]
        const userName = computed(() => {
            return store.getters.userName
        })
        const userID = computed(() => {
            return store.getters.userID
        })
        const colomId = computed(() => {
            return store.getters.colomId
        })
        const defultImg = () => {
            if (id && postData.value && postData.value.image) {
                return postData.value.image.url
            } else {
                return ''
            }
        }
        onMounted(() => {
            if (id) { getPost() }
        })
        const data: pushData = {
            "title": "",
            "content": "",
            "column": "",
            "author": ""
        }
        const changeData: pushData = {
            "title": "",
            "content": "",
        }
        const beforeUpload: beforeUpload = (file: File) => {
            let result: ReturnType<beforeUpload> = true
            if (file.size / 1024 / 1024 > 10) {
                result = '文件过大'
            } else if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
                result = '文件类型只支持jpeg或者png格式'
            }
            return result
        }
        const onErr: onErr = (msg: string) => Message.error(msg)
        const finish = (result: result) => {
            if (id) {
                changeData.image = result.data._id
            } else {
                data.image = result.data._id
            }
        }
        const inputSumbit = (result: inputResult) => {
            if (id && postData.value) {
                changeData.title = result.title
                changeData.content = result.content
                reqChangePost(postData.value._id, changeData).then(success => {
                    Message.success('编辑成功,自动跳转专栏')
                    push({
                        path: `/column/${colomId.value}`
                    })
                }).catch(() => {
                    Message.error('编辑失败，请重试')
                })
            }
            else if (userName && result) {
                data.title = result.title
                data.content = result.content
                data.author = userID.value
                data.column = colomId.value
                reqAddPost(data).then(success => {
                    Message.success('上传成功,自动跳转专栏')
                    push({
                        path: `/column/${colomId.value}`
                    })
                }, err => {
                    Message.error('上传失败请重试')
                })
            }
        }
        return { finish, fromData, inputSumbit, beforeUpload, from, onErr, id, postData, defultImg }
    }
})
</script>
<style scoped lang="less">
.creat_box {
    width: 90%;
    margin: 0 auto;
    max-width: 800px;

    .upload_box {
        height: 300px;
        width: 100%;
    }
}
</style>